// pages/common/rich-text/index.js
import Config from "../../../main.config";
import {getStorageSync, removeStorage} from "../../../utils/Storage";
import {editorSetContents, editorGetContents} from "../../../utils/Wx";
import Toast from "@vant/weapp/toast/toast";
import Notify from "@vant/weapp/notify/notify";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        formats: {},
        placeholder: ""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        options.from === "recruitment" ? this.setData({placeholder: "请填写职位描述（1000字以内）"}) : null
        this.editorInit();
    },

    /*
    * 初始化
    * */
    editorInit: function () {
        const that = this;
        let richText = getStorageSync(Config.storage.richText) || "";
        wx.createSelectorQuery().select("#editor").context(async function (res) {
            try {
                that._editorContext = res.context;
                await editorSetContents(that._editorContext, {
                    html: decodeURIComponent(richText)
                })
            } catch (e) {
                console.error(e)
            }
        }).exec();
    },

    /*
    * 样式切换
    * */
    bindChangeFormat(e) {
        const {name, value} = e.target.dataset;
        let context = this._editorContext;
        if (!name || !context) return false;
        // console.log('format', name, value)
        context.format(name, value);
    },

    /*
    * 样式变动接收函数
    * */
    onStatusChange(e) {
        const formats = e.detail
        this.setData({formats})
    },

    /*
    * 点击按钮
    * */
    onButtonClick: async function (e) {
        try {
            const that = this;
            let context = this._editorContext;
            if (!context) return false;
            let name = e.currentTarget.dataset.name;
            if (name === "save") {
                let content = await editorGetContents(context);
                if (!content || !content.text || content.text.length === 1) {
                    Notify("内容不能为空哦~");
                    return false;
                }
                Toast.success("保存成功");
                setTimeout(function () {
                    const eventChannel = that.getOpenerEventChannel();
                    content = encodeURIComponent(content.html);
                    eventChannel.emit("acceptDataFromOpenedPage", content);
                    wx.navigateBack();
                    removeStorage(Config.storage.richText);
                }, 1000)
            } else {
                await editorSetContents(context, {html: ""});
            }
        } catch (e) {
            console.error(e)
        }
    }

})